package util;

import abbot.WaitTimedOutException;
import abbot.tester.ActionFailedException;
import abbot.util.Condition;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import socketEnv.DataUtil;

import java.io.File;
import java.io.IOException;
import java.net.URL;


/**
 * 解压Zip文件工具类
 *
 * @author zhangyongbo
 */
public class ZipUtil {
	public static void main1(String[] args) throws IOException {
		String zipPath = "f:\\iserver\\supermap_iserver_8.1.1_win64_deploy.zip";
		String destDir = "f:\\iserver";
		unzip(zipPath, destDir);
	}

	public static void unzip(String zipPath, String destDir) {
		try {
			ZipFile zipFile = new ZipFile(zipPath);
//			zipFile.setFileNameCharset("gbk");避免中文名乱码
			zipFile.extractAll(destDir);
			System.out.println(zipFile.getFile().getAbsolutePath());
		} catch (ZipException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		String workspacePath = DataUtil.testDataPath + "SampleData/China/China.smwu";
		String iserverPath_remote = DataUtil.testDataPath + "Map/IServer/";
		String iserverPath_local = DataUtil.localDataPath + "Map/IServer/";
		String iserverPackageName = "supermap_iserver_win64";
		String startBatPath = iserverPath_local + iserverPackageName + "/bin/starup.bat";
		String shutdownBatPath = iserverPath_local + iserverPackageName + "/bin/starup.bat";

		//复制iserver包到本地
		String iserverZip_remote = iserverPath_remote + iserverPackageName + ".zip";
		DataUtil.copyData(iserverZip_remote);
		//解压iserver包
		String iserverZip_local = iserverPath_local + iserverPackageName + ".zip";
		ZipUtil.unzip(iserverZip_local, iserverPath_local);
		//启动iserver
		String [] cmd={"cmd","/C",startBatPath};
		Runtime.getRuntime().exec(cmd,null,new File(new File(startBatPath).getParent()));
		//等待iserver启动完成
		Condition cond = new Condition() {
			@Override
			public boolean test() {
				URL url;
				try {
					url = new URL("http://localhost:8090");
					url.openStream();
					System.out.println("iserver 启动成功。");
					return true;
				} catch (Exception e1) {
					//继续等待启动
				}
				return false;
			}
		};
		try {
			abbot.tester.Robot.wait(cond, 80000);
		} catch (WaitTimedOutException wto) {
			throw new ActionFailedException("iserver 启动失败。");
		}

	}

}